from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect, Http404
from django.views.generic import date_based
from django.views.generic import list_detail
from django.template.loader import select_template

from pennypress.apps.categories.models import Category

def category_archive_day(request, category, year, month, day, queryset, date_field, **kwargs):
    category = get_object_or_404(Category, category_slug=category)
    queryset = queryset.filter(categories__category_slug__startswith=category.category_slug).distinct()
    template = select_template(['categories/%scategory_archive_day.html' % category.category_slug ,'categories/category_archive_day.html']).name
    return date_based.archive_day(request,
        queryset=queryset,
        year=year, 
        month=month, 
        day=day,
        date_field=date_field, 
        template_name = template, 
        extra_context={'category':category})

def category_archive_month(request, category, year, month, queryset, date_field, **kwargs):
    category = get_object_or_404(Category, slug=category)
    queryset = queryset.filter(categories__slug__startswith=category.slug).distinct()
    template = select_template(['categories/%scategory_archive_month.html' % category.slug ,'categories/category_archive_month.html']).name
    return date_based.archive_month(request,
        queryset=queryset, 
        year=year, 
        month=month, 
        date_field=date_field,
        template_name = template, 
        extra_context={'category':category})

def category_archive_year(request, category, year, queryset, date_field, **kwargs):
    category = get_object_or_404(Category, slug=category)
    queryset = queryset.filter(categories__slug__startswith=category.slug).distinct()
    template = select_template(['categories/%scategory_archive_year.html' % category.slug ,'categories/category_archive_year.html']).name
    return date_based.archive_year(request,
        queryset=queryset,  
        year=year,
        date_field=date_field,
        template_name = template, 
        extra_context={'category':category})

def category_detail(request, category, queryset, paginate_by, **kwargs):
    category = get_object_or_404(Category, slug=category)
    queryset = queryset.filter(categories__slug__startswith=category.slug).distinct()
    template = select_template(['categories/%scategory_list.html' % category.slug ,'categories/category_list.html']).name
    return list_detail.object_list(request,
        queryset=queryset, 
        template_name = template, 
        paginate_by=paginate_by, 
        extra_context={'category':category})

def category_latest(request, category, queryset):
    category = get_object_or_404(Category, slug=category)
    try:
        obj = queryset.filter(categories__slug__startswith=category.slug)[0]
    except:
        return Http404
    return HttpResponseRedirect(obj.get_absolute_url())